package com.core.filter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tmh
 * @date 2023/5/16 11:48
 * @description
 */

import javax.servlet.*;
/**
 * @author tmh
 * @date 2023/3/28 8:44
 * @description 登录过滤器
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("loginFilter,---init---");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //获取响应writer对象
//        PrintWriter writer = response.getWriter();
        //获取发出请求端的url地址
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        //如果是登录页面或者验证页面，则不过滤，直接放行
        if (requestURI.contains("login.html") || requestURI.contains("/register.html") || requestURI.contains("/login") || requestURI.contains("/register")) {
            System.out.println("通过当前LoginFilter过滤器");
            filterChain.doFilter(request, response);
        } else {
            //如果不是登录页面我们也进行过滤
            if (request.getSession().getAttribute("userId") != null) {
                filterChain.doFilter(request, response);
            } else {
                RequestDispatcher requestDispatcher = request.getRequestDispatcher("/usermanagement_page/login.html");
                requestDispatcher.forward(request, response);
                //终止过滤
                return;
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("loginFilter,---destroy---");

    }
}
